# -*- coding: utf-8 -*-
# @Time    : 2025/6/28 13:56
# @Author  : Alvin
# @File    : JlSignImpl.py
# @Des     :
import json
import re
import logging
import traceback
from concurrent.futures import ThreadPoolExecutor

import requests

from constants import Constants
from handler.BaseLogisticsImpl import BaseLogisticsImpl
from utils import CommonUtil, CheUtil


class JlSignImpl(BaseLogisticsImpl):

    def __init__(self):
        super(JlSignImpl, self).__init__()
        self.max_workers = 9
        self.log_text = "同步单签收任务"
        self.need_update_list = []

    def start_handle_sign_task(self, batch_index, db_data_list):
        """
        开始处理同步单提货任务
        :param batch_index: 当前任务批次
        :param db_data_list:
        :return:
        """
        try:
            # is_login = self.check_user_is_logined()
            # if not is_login:
            #     logging.error("用户登录失败，请检查登录数据是否异常")
            #     return
            with ThreadPoolExecutor(max_workers=self.max_workers) as pool:
                for item in db_data_list:
                    pool.submit(self.handle_sync_order_sign_action, item)
            logging.info(f"第【{batch_index}】数据跑完了，共需更新:{len(self.need_update_list)}条数据")
            self.db_util.update_sync_order_sign_info(self.need_update_list)
        except Exception as ex:
            logging.error(f"【start_handle_dy_update_task】异常:{str(ex)}")
            logging.error(f"【start_handle_dy_update_task】异常2:%s", traceback.format_exc())

    def handle_sync_order_sign_action(self, dbItem):
        try:
            mailNo = dbItem.get("mailNo", None)
            code, name = self.query_express_code(mailNo)
            if not code:
                logging.error(f"【{mailNo}】未查询到快递编码，请检查快递单号是否正确")
                return
            if code == 'shunfeng' or code == 'SF':
                logging.info(f"顺丰单号暂不支持查询:上家单号->{dbItem['mailNo']}")
                return
            logisticsResp = self.queryLogisticsInfoByKuaiDi100(mailNo, code)
            if not logisticsResp:
                return
            self.handle_logistics_resp_info(dbItem, logisticsResp)
        except Exception as ex:
            logging.error(f"handle_sync_order_sign_action 异常：{str(ex)}")
            logging.error("traceback.format_exc():\n%s" % traceback.format_exc())

    def handle_logistics_resp_info(self, dbItem, logisticsResp):
        """
        处理快递100响应信息
        :param dbItem:
        :param logisticsResp:
        :return:
        """
        mailNo = dbItem['mailNo']
        mailNo_self = dbItem['mailNo_self']
        logisticsList = logisticsResp.get("data", None)
        if not logisticsList:
            logging.info(f"快递100查询信息返回为空：{logisticsResp['message']},上家单号：{mailNo}")
            return
        least_item = logisticsList[0]
        newData = logisticsList[0]
        currentState = newData['statusCode']
        if currentState not in self.qianShouList:
            return
        self.handle_order_sign_action(dbItem, least_item)

    def handle_order_sign_action(self, dbItem, least_item):
        """
        处理订单签收事件
        :param dbItem:
        :param least_item:最后一条物流item
        :return:
        """
        expressLastUpdateTime = least_item.get("time")
        context = least_item.get("context")
        phone_numbers = re.findall(r'1\d{10}', context)
        if phone_numbers is not None and len(phone_numbers) > 0:
            mobile = phone_numbers[0]
        else:
            mobile = Constants.default_tel
        qs_man = f"派件{mobile}"
        mail_no_self = dbItem.get("mailNo_self")
        row_id = dbItem.get("id")
        url = "https://app.lqfast.com/AppApis.ashx"
        param = {
            "companyid": Constants.logistics_code,
            "proc": "USP_SF_ORDER_SIGN_APP",
            "method": "Query",
            "pars": [
                {
                    "LoginWeb": "",
                    "sfman": "晋良物流",  # 经办人
                    "qsmancode": "",  # 签收人证件
                    "PublicIP": "",
                    "LoginSite": "",
                    "ishx": "1",
                    "mac": "android",
                    "iserror": "0",
                    "pdflag": "",
                    "LoginUserID": Constants.sb_phone,
                    "LoginUserName": Constants.sb_name,
                    "unit": mail_no_self,
                    "LocalIP": "",
                    "qsman": qs_man  # 签收人
                }
            ],
            "username": Constants.sb_phone,
            "token": self.app_token
        }

        p = {
            "pars": json.dumps(param)
        }
        headers = CheUtil.get_app_header()
        resp_text = requests.post(url, data=p, headers=headers).text
        try:
            logging.info(f"【{mail_no_self}】签收响应：{resp_text}")
            if '"result":"0",' in resp_text:
                self.need_update_list.append({
                    "id": row_id,
                    "statusStr": "已签收",
                    "statusCode": "已签收",
                    "logisticsInfo": "已签收",
                    "expressLastUpdateTime": expressLastUpdateTime,
                    "updateTime": CommonUtil.get_current_format_time()
                })
            else:
                logging.error(f"【{mail_no_self}】签收失败，接口响应：{resp_text}")
        except Exception as ex:
            logging.error(f"handle_order_sign_action 异常：{str(ex)}")
            logging.error("traceback.format_exc():\n%s" % traceback.format_exc())
